//封装一个函数：简化时间格式
export const formatDate1 = (dateParam: Date | string | number)=>{
  const date = dateParam instanceof Date ? dateParam : new Date(dateParam);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 获取当前系统时间并格式化
export const getCurrentDateTime = (): string => {
  const date = new Date();
  return formatDate1(date);
};

// 获取当前日期
export const getCurrentDate = (): string => {
  const date = new Date();
  return formatDate2(date);
};

// 日期依次加一天
// 定义增加天数的箭头函数
export const addDays = (date: Date, days: number): Date => {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
};

// 输出当前日期，格式为 "yyyymmdd"
export const formatDate = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}${month}${day}`;
}

// 输出当前日期，格式为 "yyyy-mm-dd",js的Date对象对字符串转时间的格式有要求，带-的可以
export const formatDate2 = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

export function calculateMinutes(startTimeStr: string, endTimeStr: string): number | null {
  // 时间字符串解析（兼容鸿蒙系统时区）
  const parseTimeString = (timeStr: string): Date | null => {
    try {
      const [datePart, timePart] = timeStr.split(' ');
      const [year, month, day] = datePart.split('-').map(Number);
      const [hours, minutes, seconds] = timePart.split(':').map(Number);
      return new Date(year, month - 1, day, hours, minutes, seconds);
    } catch (e) {
      return null;
    }
  };

  const startDate = parseTimeString(startTimeStr);
  const endDate = parseTimeString(endTimeStr);

  if (!startDate || !endDate) {
    return null; // 无效时间格式处理
  }

  // 计算分钟差值（含正负判断）
  const diffMilliseconds = endDate.getTime() - startDate.getTime();
  return Math.floor(diffMilliseconds / (1000 * 60));
}